package com.htfyun.fragment.library.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

import org.geometerplus.android.fbreader.tree.TreeActivity;
import org.geometerplus.fbreader.tree.FBTree;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import me.yokeyword.fragmentation.SupportFragment;


/**
 * Created by sst on 2017/11/1.
 */

public abstract class TreeRecyclerViewAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {

    private final SupportFragment myFragment;
    private final List<FBTree> myItems;

    private final Activity myActivity;

    protected TreeRecyclerViewAdapter(SupportFragment fragment) {
        myFragment = fragment;
        myItems = Collections.synchronizedList(new ArrayList<FBTree>());
        myActivity = myFragment.getActivity();
    }

    protected  SupportFragment getMyFragment() {
        return myFragment;
    }
    
    protected Context getContext() {
        return myActivity;
    }

    public void remove(final FBTree item) {
        myActivity.runOnUiThread(new Runnable() {
            public void run() {
                myItems.remove(item);
                notifyDataSetChanged();
            }
        });
    }

    public void add(final FBTree item) {
        myActivity.runOnUiThread(new Runnable() {
            public void run() {
                myItems.add(item);
                notifyDataSetChanged();
            }
        });
    }

    public void add(final int index, final FBTree item) {
        myActivity.runOnUiThread(new Runnable() {
            public void run() {
                myItems.add(index, item);
                notifyDataSetChanged();
            }
        });
    }

    public void replaceAll(final Collection<FBTree> items) {
        myActivity.runOnUiThread(new Runnable() {
            public void run() {
                synchronized (myItems) {
                    myItems.clear();
                    myItems.addAll(items);
                }
                notifyDataSetChanged();
             
            }
        });
    }

    @Override
    public int getItemCount() {
        return myItems.size();
    }

    public FBTree getItem(int position) {
        return myItems.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public int getIndex(FBTree item) {
        return myItems.indexOf(item);
    }



}
